#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 个人学习解读版本
import RPi.GPIO as GPIO
import time

# 颜色分别是 红色、红色、绿色 、绿色
# 红色 0xFF00,0xF00F
# 绿色 0x00FF, 0x0FF0
# 不亮 0x0000
colors = [0x0000,0x000F,0x00FF,0x0FFF,0xFFFF]

# 指的是物理针脚编号
# 11 GPIO 0  17 RED
# 12 GPIO 1  18 GREEN
pins = {"red":11, "green":12}  # pins是一个字典

# 使用针脚物理位置的GPIO模式
GPIO.setmode(GPIO.BOARD)       

for i in pins:
    GPIO.setup(pins[i], GPIO.OUT)   # 设置针脚为输出模式
    GPIO.output(pins[i], GPIO.HIGH) # 设置针脚为高压来关闭led(+3.3V)

# 设置频率为2KHZ
pinRed = GPIO.PWM(pins['red'], 2000)  
pinGreen= GPIO.PWM(pins['green'], 2000)
 
pinRed.start(0)      # 初始化占空比(leds off)
pinGreen.start(0)


def map(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
 
def setColor(color):   # For example : color = 0x112233
    colorRed = (color & 0x1100) >> 8
    colorGreen = (color & 0x0011) >> 0
     
    colorRed = map(colorRed, 0, 255, 0, 100)
    colorGreen = map(colorGreen, 0, 255, 0, 100)
     
    pinRed.ChangeDutyCycle(colorRed)     # Change duty cycle
    pinGreen.ChangeDutyCycle(colorGreen)
 
def mainLoop():
    while True:
        for color in colors:
            setColor(color)
            time.sleep(1)
 
def destroy():
    pinRed.stop()
    pinGreen.stop()
    for i in pins:
        GPIO.output(pins[i], GPIO.HIGH)    # Turn off all leds
    GPIO.cleanup()
 
if __name__ == "__main__":
    try:
        mainLoop()
    except KeyboardInterrupt:
        destroy()